﻿#region Librerias

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceProcess;
using System.Timers;
using System.IO;
using System.Threading.Tasks;
using System.Threading;

#endregion

namespace ESF.General
{
	public class BaseWindowsService : ServiceBase
	{
		#region Miembros

		private System.Timers.Timer _Timer;

		#endregion


		#region Propiedades

		public bool EnableTimer
		{
			set 
			{
				_Timer.Enabled = value;
			}
			get
			{
				return _Timer.Enabled;
			}
		}

		#endregion


		#region Constructor
		
		public BaseWindowsService()
		{
			_Timer = new System.Timers.Timer ();			
			_Timer.Interval = (double)(ReadConfig.GetAppSettingDouble("ServiceIntervalMinutes", 10) * 60 * 1000);
			_Timer.Elapsed += new ElapsedEventHandler(Timer_Elapsed);
		}


		protected override void Dispose(bool disposing)
		{
			DoStop ();
		}

		#endregion
		
		
		#region Funciones
		
		public void Test ()
		{
			Log.WriteStartHistory("{0} Started in Console Mode", ServiceName);
		
			OnStart (null);
		}


		protected virtual void Timer_Elapsed(object sender, ElapsedEventArgs e) 
		{
			Log.WriteLineHistory ("Timer is running but not implemented, run at: {0}", DateTime.Now);
		}


		public virtual void DoStart () { }
		
		
		public virtual void DoStop () { }
		
		#endregion
		
		
		#region Eventos

		protected override void OnStart(string[] args)
		{
			try
			{
				Log.WriteStartHistory ("{0} Started", ServiceName);

				
				Console.WriteLine ("Culture: {0}", ReadConfig.Culture);

				Log.WriteLineHistory ("Culture: {0}", ReadConfig.Culture);

				Thread.CurrentThread.CurrentCulture = ReadConfig.CultureInfo;


				Console.WriteLine("Parallel Default Options: MaxDegreeOfParallelism (Cores) {0}/{1}", ProcessHelper.ProcessorsCoresLimit, Environment.ProcessorCount);

				_Timer.Enabled = ReadConfig.ExistsAppSetting ("ServiceIntervalMinutes");

				if (_Timer.Enabled)
				{
					Log.WriteLineHistory("Timer enabled with inverval: {0}", TextHelper.ToStringMS((long)_Timer.Interval));
				}

				ProcessHelper.SetProcessorCoreLimit();

				Task.Factory.StartNew (() => 
				{
					DoStart ();
				
					if (_Timer.Enabled)
					{
						Timer_Elapsed (null, null);
					}
				});
			}
			catch (Exception pEx)
			{
				Log.Error (pEx);
			}
		}
		

		protected override void OnStop()
		{
			try
			{
				_Timer.Stop ();

				DoStop ();

				Log.WriteLineHistory ("Service stop at {0}", DateTime.Now);

				_Timer.Enabled = false;
			}
			catch (Exception pEx)
			{
				Log.Error (pEx);
			}
		}
		
		#endregion
	}
}